<template>
	<view class="Wrapper">
		<navBar title="AI咨询"></navBar>
		<scroll-view
			scroll-y="true"
			class="scrollView"
			enable-back-to-top
			:scroll-top="scrollTop"
			:scroll-into-view="scrollintoview"
			:style="scrollHeight">
			<template v-for="(item, index) in chatHomeList" :key="index">
				<view class="List Left" :id="`chat${index}`" v-if="item.state == 1">
					<view class="HeadBox">
						<image :src="item.img" mode="aspectFill" class="Headimgs"></image>
						<view class="d-flex a-center p-top10" v-if="item.isshow">
							<text class="tipTxt">静音</text>
							<image
								:src="staticImg('icon_sound@2x.png')"
								mode="aspectFill"
								class="soundImg"></image>
						</view>
					</view>
					<view class="content">
						<view class="content_text">
							<view class="answer">{{ item.answer }}</view>
							<template v-if="item.type && item.type == 1">
								<view
									class="single_choice"
									v-for="(sub, subIn) in item.recommend"
									:key="subIn"
									@click.stop="single_choice(item, sub, index)"
									>{{ sub.index }}.{{ sub.question }}
								</view>
							</template>

							<view class="rows" v-if="item.type && item.type == 3">
								<up-checkbox-group
									v-model="checkboxValue1"
									placement="column"
									@change="checkboxChange">
									<view
										class="Multiple_choice"
										:class="{ Nochoice: !item.allowclick }"
										v-for="(sub, subIn) in item.recommend">
										<up-checkbox
											:customStyle="{ marginBottom: '8px' }"
											:key="subIn"
											size="14"
											labelSize="13"
											iconSize="10"
											:labelColor="mainStore.color"
											:label="`${sub.index}.${sub.question}`"
											:name="sub.question">
										</up-checkbox>
									</view>
								</up-checkbox-group>
								<view
									class="configBtn"
									:class="{ active: checkboxValue1.length }"
									v-if="item.allowclick"
									@click="configMultiple(item)"
									>确定</view
								>
							</view>
						</view>
					</view>
				</view>
				<view class="List Right" :id="`chat${index}`" v-if="item.state == 2">
					<view class="content">
						<view class="content_text">{{ item.question }}</view>
						<view class="Edit_error" v-if="item.isshow">
							<text class="discern">识别错误？</text>
							<text class="Edit">修改</text>
						</view>
					</view>
					<view class="HeadBox">
						<image :src="item.img" mode="aspectFill" class="Headimgs"></image>
					</view>
				</view>
			</template>
		</scroll-view>
		<view class="bottomChat" :style="chatBoxStyle">
			<view class="chatBot">
				<view class="chatBor">
					<input
						class="textarea"
						type="text"
						placeholder="请输入想要问的问题"
						placeholder-class="place"
						:adjust-position="false"
						confirm-type="send"
						:focus="false"
						v-model="inputValue"
						@focus="handleFocus"
						@blur="handleBlur"
						@confirm="Send" />
					<image
						:src="staticImg('FS.png')"
						mode="aspectFit"
						class="send"
						@click="Send"></image>
				</view>
				<view class="Tips" v-if="ishistory"> 您可以这样问：帮我起草一份离婚协议书 </view>
			</view>
		</view>
	</view>

	<up-datetime-picker
		ref="datetimePickerRef"
		:show="show"
		v-model="value1"
		:minDate="minDate"
		:maxDate="Date.now()"
		mode="date"
		:formatter="formatter"
		@cancel="show = false"
		@confirm="confirmDate">
	</up-datetime-picker>
	<cityPicker
		:column="3"
		:default-value="defaultValue"
		:mask-close-able="true"
		@confirm="confirmCity"
		@cancel="visible = false"
		:visible="visible" />
</template>

<script setup>
	import cityPicker from '@/uni_modules/piaoyi-cityPicker/components/piaoyi-cityPicker/piaoyi-cityPicker';
	import HomeBar from '@/components/Home/homeBar.vue';
	import defaultNiu from '@/components/Home/defaultNiu.vue';
	import {
		toUrl,
		toLogin,
		Toast,
		formatter,
		tampToDate,
		staticImg,
		imgUrls,
		showLoading,
		hideLoading,
		toRect,
	} from '@/utils/utils.js';
	import { getopendId, getBaseInfo, myInfo } from '@/utils/api.js';
	import Http from '@/utils/request.js';
	import { ref, computed, watch, nextTick, onUnmounted } from 'vue';
	import { onLoad, onShow, onReady, onShareAppMessage, onShareTimeline } from '@dcloudio/uni-app';
	import { useMainStore } from '@/stores/index';

	const mainStore = useMainStore();
	const scrollTop = ref(0);
	const scrollintoview = ref('');
	const chatBoxHeight = ref(0);
	const keyBoardHeight = ref(0);
	const isKeyboardShow = ref(false);
	const inputValue = ref('');
	const ishistory = ref(false);
	const isFocusing = ref(false);

	const show = ref(false);
	const minDate = ref(-1234559422934);
	const value1 = ref(Date.now());
	const datetimePickerRef = ref(null);

	const defaultValue = ref('500103');
	const visible = ref(false);
	const chatHomeList = ref([]);
	const checkboxValue1 = ref([]);
	const caseId = ref('');

	const checkboxChange = (n) => {
		// console.log('change', n);
	};
	onLoad(() => {
		// getopendId();
	});
	onReady(() => {
		datetimePickerRef.value.setFormatter(formatter);
		updateChatBoxHeight();

		// #ifdef APP-PLUS || MP-WEIXIN
		try {
			uni.onKeyboardHeightChange((res) => {
				nextTick(() => {
					keyBoardHeight.value = res.height || 0;
					updateChatBoxHeight();
					if (res.height > 0) {
						scrollToBottom();
					}
				});
			});
		} catch (error) {
			console.log('键盘监听异常：', error);
		}
		// #endif

		nextTick(() => {
			scrollToBottom(1000);
		});
	});

	const Send = () => {
		if (!mainStore.token) return toLogin();
		if (!mainStore.hr && !mainStore.lawyer && !mainStore.staff) return;
		// if (!mainStore.staff) return toUrl(`/bizPage/index/join`);
		if (!inputValue.value) return;
		// if (!inputValue.value.trim()) return;
		let ObjAi = {
			img: imgUrls(mainStore.BaseInfo.chatImg),
			allowclick: true, // 是否点击
			isshow: false,
			state: 1,
		};
		let Objme = {
			img: imgUrls(mainStore.userInfo.avatar),
			question: inputValue.value,
			isshow: false,
			state: 2,
		};
		showLoading();
		Http.post({
			url: '/advice/conversation',
			data: {
				question: inputValue.value,
				caseId: caseId.value,
			},
		}).then((res) => {
			hideLoading();
			if (res.code != 0) return Toast(res.msg);
			const result = res.data;
			if (result.caseId) caseId.value = result.caseId;

			// if (result.opinionUrl)
			// 	return toRect(`/pages/lookFile/lookFile?fileurl=${result.opinionUrl}`);
			if (result.pdfUrl) return toRect(`/pages/lookFile/lookFile?fileurl=${result.pdfUrl}`);
			ObjAi = {
				...ObjAi,
				...result,
			};
			chatHomeList.value.push(Objme);
			chatHomeList.value.push(ObjAi);
			if (result.reporting == 1) {
				inputValue.value = ' ';
				Send();
				return;
			}
			if (!result.type) return;
			if (result.type == 5) return (show.value = true); // 日期
			if (result.type == 6) return (visible.value = true); //省市区
		});

		inputValue.value = '';
	};

	const single_choice = (Item, Sub, Index) => {
		if (!Item.allowclick) return;
		Item.allowclick = false;
		inputValue.value = Sub.question;
		Send();
	};

	const configMultiple = (Item) => {
		if (!checkboxValue1.value.length) return;
		Item.allowclick = false;
		inputValue.value = checkboxValue1.value.join('\n');
		Send();
	};

	const updateChatBoxHeight = () => {
		const query = uni.createSelectorQuery();
		query
			.select('.bottomChat')
			.boundingClientRect((data) => {
				if (data) chatBoxHeight.value = data.height;
			})
			.exec();
	};

	const handleFocus = () => {
		isFocusing.value = true;
		// #ifdef APP-PLUS || MP-WEIXIN
		setTimeout(() => {
			if (!isFocusing.value) return;
			uni.getWindowInfo({
				success: (res) => {
					if (res.keyboardHeight) {
						keyBoardHeight.value = res.keyboardHeight;
					}
					updateChatBoxHeight();
					scrollToBottom(600);
				},
			});
		}, 100);
		// #endif

		// #ifdef H5
		setTimeout(() => {
			if (!isFocusing.value) return;
			updateChatBoxHeight();
			scrollToBottom(600);
		}, 300);
		// #endif
	};

	const handleBlur = () => {
		isFocusing.value = false;
		setTimeout(() => {
			if (isFocusing.value) return;
			keyBoardHeight.value = 0;
			updateChatBoxHeight();
			scrollToBottom(500);
		}, 100);
	};
	const scrollToBottom = (Num = 1000) => {
		// 修改这里的初始化滚动逻辑
		const query = uni.createSelectorQuery();
		query
			.selectAll('.List')
			.boundingClientRect((data) => {
				if (data && data.length > 0) {
					// 计算所有聊天内容的实际总高度
					const totalHeight = data.reduce((sum, item) => sum + item.height, 0);
					// 设置初始滚动位置
					scrollTop.value = totalHeight + Num;
				}
			})
			.exec();
	};
	watch(
		() => chatHomeList,
		() => {
			nextTick(() => {
				updateChatBoxHeight();
				scrollToBottom();
			});
		},
		{
			deep: true,
		}
	);
	const scrollHeight = computed(() => {
		const Height =
			mainStore.windowHeight -
			mainStore.totalHeight -
			chatBoxHeight.value -
			keyBoardHeight.value;
		return ['height:' + parseInt(Height) + 'px'].join(';');
	});
	const chatBoxStyle = computed(() => {
		if (keyBoardHeight.value) {
			return {
				position: 'fixed',
				bottom: `${keyBoardHeight.value}px`,
				left: 0,
				right: 0,
				width: '100%',
				zIndex: 999,
				transform: 'translateZ(0)',
			};
		}
		return {
			paddingBottom: mainStore.safeAreaInsets.bottom + 'px',
			width: '100%',
		};
	});

	const confirmDate = (event) => {
		inputValue.value = tampToDate(event.value, true);
		show.value = false;
		Send();
	};

	const confirmCity = (event) => {
		inputValue.value = event.name;
		visible.value = false;
		Send();
	};
	// onShareAppMessage(() => {
	// 	return mainStore.share
	// })
	// onShareTimeline(() => {
	// 	return mainStore.share
	// })
</script>

<style lang="scss" scoped>
	.Wrapper {
		width: 100vw;
		height: 100vh;
		display: flex;
		flex-direction: column;
		background-color: #f4f5f5;
		box-sizing: border-box;
		overflow: hidden;
	}

	.scrollView {
		width: 100%;
		box-sizing: border-box;
		padding: 0 20rpx;

		.List {
			width: 100%;
			display: flex;
			padding-top: 20rpx;

			.content {
				width: 100%;

				&_text {
					display: inline-block;
					padding: 14rpx 20rpx;
					background-color: #ffffff;

					font-size: 28rpx;
					line-height: 40rpx;
					margin-top: 20rpx;
				}
			}

			.HeadBox {
				display: flex;
				flex-direction: column;
				align-items: center;

				.Headimgs {
					width: 88rpx;
					height: 88rpx;
					border-radius: 4rpx;
					overflow: hidden;
				}
			}
		}

		.Left {
			padding-right: 180rpx;
			justify-content: flex-start;

			.content_text {
				border-radius: 0 20rpx 20rpx 20rpx;
				border: 1rpx solid rgba(0, 0, 0, 0.1);

				.answer {
					color: #333;
					font-size: 28rpx;
				}

				.single_choice {
					width: 100%;
					padding: 14rpx 20rpx;
					color: $color_008;
					font-size: 26rpx;
					background-color: #f7f7f7;
					margin-top: 16rpx;
					border-radius: 6rpx;
				}

				.Multiple_choice {
					width: 100%;
					padding: 4rpx 20rpx;
					color: $color_008;
					font-size: 26rpx;
					background-color: #f7f7f7;
					margin-top: 14rpx;
					border-radius: 6rpx;

					::v-deep .u-checkbox__icon-wrap {
						flex-shrink: 0 !important;
					}
				}

				.Nochoice {
					::v-deep .u-checkbox__icon-wrap {
						display: none !important;
					}
				}

				.configBtn {
					width: 100%;
					height: 70rpx;
					background-color: #f7f7f7;
					color: #999;
					font-size: 30rpx;
					display: flex;
					justify-content: center;
					align-items: center;
					border-radius: 10rpx;
					margin-top: 20rpx;
				}

				.active {
					background-color: $color_008 !important;
					color: #fff !important;
				}
			}

			.tipTxt {
				color: #9a9ea2;
				font-size: 20rpx;
			}

			.soundImg {
				width: 28rpx;
				height: 24rpx;
				margin-left: 4rpx;
			}

			.content {
				margin-left: 20rpx;
			}
		}

		.Right {
			padding-left: 180rpx;
			justify-content: flex-end;

			.content {
				margin-right: 20rpx;
				display: flex;
				flex-direction: column;
				align-items: flex-end;

				.content_text {
					color: #fff;
					border-radius: 20rpx 0 20rpx 20rpx;
					background-color: v-bind('mainStore.color');
				}

				.Edit_error {
					display: flex;
					align-items: center;
					padding-top: 10rpx;

					.discern {
						color: #9a9ea2;
						font-size: 20rpx;
					}

					.Edit {
						color: v-bind('mainStore.color');
						font-size: 20rpx;
					}
				}
			}
		}
	}

	.bottomChat {
		width: 100%;

		.chatBot {
			width: 100%;
			padding: 20rpx;
			box-sizing: border-box;

			.chatBor {
				width: 100%;
				height: 140rpx;
				display: flex;
				align-items: center;
				position: relative;
				background-color: #ffffff;
				border: 1px solid #99adff;
				border-radius: 20rpx;
				padding: 20rpx;
				box-sizing: border-box;

				.textarea {
					flex: 1;
					padding: 0rpx 0;
					height: 100%;
					color: #000;
					font-size: 28rpx;
					padding-right: 20rpx;
					box-sizing: border-box;
				}

				.send {
					width: 56rpx;
					height: 56rpx;
					flex-shrink: 0;
				}
			}

			.Tips {
				width: 100%;
				color: #666;
				font-size: 24rpx;
				text-align: center;
				display: block;
			}
		}
	}
</style>
